package dao

import (
	"micro.user.action.server/common"
	"micro.user.action.server/database"
	"micro.user.action.server/models"
	"micro.user.action.server/utils"
	"xorm.io/core"
)

func AdminUserRegistry(user *models.VsHUser) (uint64, error) {
	eg := database.GetDB()
	if eg == nil {
		return 0, common.DBNil
	}

	afterID, err := eg.Table(database.VsAdminUserTable).Insert(user)
	if err != nil {
		return 0, err
	}
	if afterID < 1 {
		return 0, common.DBInsertErr
	}

	return user.UserId, nil
}

func AdminUserLogin(userName, password string) (*models.VsHUser, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, common.DBNil
	}

	info := &models.VsHUser{}
	field := GetField(userName)
	passed := utils.MD5(password)

	has, err := eg.Table(database.VsAdminUserTable).Where(field+"=? and password = ? and is_delete = 0", userName, passed).Get(info)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, common.UserIsNotExist
	}

	return info, nil
}

func QueryAdminUserInfo(userID uint64) (*models.VsHUser, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, common.DBNil
	}

	info := &models.VsHUser{}
	has, err := eg.Table(database.VsAdminUserTable).ID(core.PK{userID}).Get(info)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, common.UserIsNotExist
	}

	return info, nil
}
